import { Request, Response } from 'express';

// 模拟部门数据
const departments: any[] = [
  { id: 1, name: '技术部', parentId: null },
  { id: 2, name: '前端组', parentId: 1 },
  { id: 3, name: '后端组', parentId: 1 },
];

// 模拟分页数据
const getPageData = (params: any) => {
  const { current = 1, pageSize = 10 } = params;
  const start = (current - 1) * pageSize;
  const end = start + Number(pageSize);
  return {
    content: departments.slice(start, end),
      totalElements: departments.length,
    current: Number(current),
    pageSize: Number(pageSize),
  };
};

export default {
  // 模拟添加部门接口
  'POST /api/system/department': (req: Request, res: Response) => {
    const newDepartment = req.body;
    departments.push({ ...newDepartment, id: departments.length + 1 });
    res.status(200).json({
      code: 200,
      message: '添加成功',
      data: newDepartment,
    });
  },

  // 模拟更新部门接口
  'PUT /api/system/department': (req: Request, res: Response) => {
    const updatedDepartment = req.body;
    const index = departments.findIndex((d) => d.id === updatedDepartment.id);
    if (index !== -1) {
      departments[index] = updatedDepartment;
      res.status(200).json({
        code: 200,
        message: '更新成功',
        data: updatedDepartment,
      });
    } else {
      res.status(404).json({
        code: 404,
        message: '部门不存在',
      });
    }
  },

  // 模拟删除部门接口
  'DELETE /api/system/department/:id': (req: Request, res: Response) => {
    const id = parseInt(req.params.id, 10);
    const index = departments.findIndex((d) => d.id === id);
    if (index !== -1) {
      departments.splice(index, 1);
      res.status(200).json({
        code: 200,
        message: '删除成功',
      });
    } else {
      res.status(404).json({
        code: 404,
        message: '部门不存在',
      });
    }
  },

  // 模拟获取部门树形结构接口
  'GET /api/system/department/tree': (req: Request, res: Response) => {
    const tree = (parentId: number | null) => {
      return departments
        .filter((d) => d.parentId === parentId)
        .map((d) => ({
          ...d,
          children: tree(d.id),
        }));
    };
    res.status(200).json({
      code: 200,
      message: '获取成功',
      data: tree(null),
    });
  },

  // 模拟根据部门 ID 获取单个部门信息接口
  'GET /api/system/department/:id': (req: Request, res: Response) => {
    const id = parseInt(req.params.id, 10);
    const department = departments.find((d) => d.id === id);
    if (department) {
      res.status(200).json({
        code: 200,
        message: '获取成功',
        data: department,
      });
    } else {
      res.status(404).json({
        code: 404,
        message: '部门不存在',
      });
    }
  },

  // 模拟获取部门列表接口
  'GET /api/system/department': (req: Request, res: Response) => {
    const pageData = getPageData(req.query);
    res.status(200).json({
      code: 200,
      message: '获取成功',
      data: pageData,
    });
  },
};
